package org.iabako.server.taglib;

import org.iabako.shared.entity.enumeration.Language;
import org.iabako.shared.entity.enumeration.WebsiteDescriptionSection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by jose on 27/01/15.
 */
public class DescriptionTag extends AbstractTag {

    public int doStartTag() throws JspException {

        JspWriter out = pageContext.getOut();

        WebsiteDescriptionSection section = (WebsiteDescriptionSection) pageContext.getSession().getAttribute("IABAKO_DESCRIPTION_SECTION");
        section = section == null ? WebsiteDescriptionSection.main : section;

        Language pickedLang = getPickedLanguage((HttpServletRequest) pageContext.getRequest());

        String msgFilePrefix = "/org/iabako/i18n/";
        try {
            InputStream is = this.getClass().getResourceAsStream(msgFilePrefix + pickedLang.getDescriptionFileName());
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line;
            String sectionKey = null;
            switch (section) {
                case main:
                    sectionKey = "website_description_main=";
                    break;
                case what:
                    sectionKey = "website_description_what=";
                    break;
                case start:
                    sectionKey = "website_description_start=";
                    break;
            }

            while ((line = br.readLine()) != null) {
                if (line.contains(sectionKey)) {
                    String sectionValue = line.replace(sectionKey, "");
                    out.println("<meta name=\"description\" content=\"" + sectionValue + "\">");
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return super.doStartTag();
    }
}
